// frontend/src/components/AdminPanel.js
import { ApiClient } from '../utils/api.js';

export const AdminPanelComponent = {
  props: ['admin', 'user'], // 添加user属性
  data() {
    return {
      loading: false
    };
  },
  async mounted() {
    // 当组件挂载时，如果当前是用户管理标签页，则获取用户数据
    if (this.admin.activeTab === 'users') {
      this.fetchUsers();
    }
  },
  methods: {
    showWelcome() {
      this.$emit('show-welcome');
    },
    switchAdminTab(tab) {
      this.$emit('switch-tab', tab);
      // 切换到用户标签页时获取用户数据
      if (tab === 'users') {
        this.fetchUsers();
      }
    },
    // frontend/src/components/AdminPanel.js
    async fetchUsers() {
        this.loading = true;
        try {
            const token = localStorage.getItem('token');
            console.log('获取用户列表时的token:', token);
            
            // 检查token是否存在
            if (!token) {
                this.$emit('set-message', '认证信息丢失，请重新登录', 'error');
                this.loading = false;
                // 重定向到登录页面
                this.$emit('logout');
                return;
            }
            
            const { ok, data, status } = await ApiClient.fetchUsers(token);
            console.log('获取用户列表结果:', { ok, data, status });
            
            if (ok) {
                this.$emit('update-users', data);
            } else {
                // 根据状态码提供更具体的错误信息
                let errorMessage = data.message || '获取用户列表失败';
                
                if (status === 422) {
                    errorMessage = '认证信息无效或已过期，请重新登录';
                    // 清除无效的token并重定向到登录页面
                    console.log('Token已过期，清除token');
                    localStorage.removeItem('token');
                    this.$emit('logout');
                } else if (status === 401) {
                    // 对于401错误，不自动清除token，而是提示用户
                    errorMessage = '认证失败，请尝试重新登录';
                } else if (status === 403) {
                    errorMessage = '权限不足，只有管理员可以访问';
                }
                
                this.$emit('set-message', errorMessage, 'error');
            }
        } catch (error) {
            console.error('获取用户列表错误:', error);
            this.$emit('set-message', '网络错误，请稍后重试', 'error');
        } finally {
            this.loading = false;
        }
    },
    async toggleUserStatus(userId) {
      // 阻止用户修改自己的状态
      if (userId === this.user.user_id) {
        this.$emit('set-message', '不能修改当前用户的状态', 'error');
        return;
      }
      
      try {
        const token = localStorage.getItem('token');
        const { ok, data } = await ApiClient.toggleUserStatus(token, userId);
        
        if (ok) {
          this.$emit('set-message', '用户状态更新成功', 'success');
          // 更新后重新获取用户列表
          await this.fetchUsers();
        } else {
          this.$emit('set-message', data.message || '更新用户状态失败', 'error');
        }
      } catch (error) {
        console.error('更新用户状态错误:', error);
        this.$emit('set-message', '网络错误，请稍后重试', 'error');
      }
    },
    async deleteUser(userId) {
      // 阻止用户删除自己
      if (userId === this.user.user_id) {
        this.$emit('set-message', '不能删除当前用户', 'error');
        return;
      }
      
      // 检查是否是管理员账户
      const user = this.admin.users.find(u => u.user_id === userId);
      if (user && user.role === 'admin') {
        this.$emit('set-message', '不能删除管理员账户', 'error');
        return;
      }
      
      if (!confirm('确定要删除这个用户吗？')) return;
      
      try {
        const token = localStorage.getItem('token');
        const { ok, data } = await ApiClient.deleteUser(token, userId);
        
        if (ok) {
          this.$emit('set-message', '用户删除成功', 'success');
          // 删除后重新获取用户列表
          await this.fetchUsers();
        } else {
          this.$emit('set-message', data.message || '删除用户失败', 'error');
        }
      } catch (error) {
        console.error('删除用户错误:', error);
        this.$emit('set-message', '网络错误，请稍后重试', 'error');
      }
    }
  },
  template: `
    <div class="container py-5">
      <div class="row">
        <div class="col-12">
          <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="bi bi-gear me-2"></i>系统管理</h2>
            <button class="btn btn-secondary" @click="showWelcome">
              <i class="bi bi-arrow-left me-1"></i>返回首页
            </button>
          </div>
          
          <!-- 管理选项卡 -->
          <ul class="nav nav-tabs mb-4">
            <li class="nav-item">
              <button class="nav-link" 
                      :class="{ active: admin.activeTab === 'users' }" 
                      @click="switchAdminTab('users')">
                <i class="bi bi-people me-1"></i>用户管理
              </button>
            </li>
            <li class="nav-item">
              <button class="nav-link" 
                      :class="{ active: admin.activeTab === 'projects' }" 
                      @click="switchAdminTab('projects')">
                <i class="bi bi-folder me-1"></i>项目管理
              </button>
            </li>
            <li class="nav-item">
              <button class="nav-link" 
                      :class="{ active: admin.activeTab === 'userProjects' }" 
                      @click="switchAdminTab('userProjects')">
                <i class="bi bi-diagram-3 me-1"></i>项目分配
              </button>
            </li>
            <li class="nav-item">
              <button class="nav-link" 
                      :class="{ active: admin.activeTab === 'samples' }" 
                      @click="switchAdminTab('samples')">
                <i class="bi bi-database me-1"></i>样本管理
              </button>
            </li>
          </ul>
          
          <!-- 用户管理 -->
          <div v-if="admin.activeTab === 'users'">
            <div class="card shadow-sm">
              <div class="card-header bg-primary text-white d-flex justify-content-between align-items-center">
                <h5 class="mb-0"><i class="bi bi-people me-2"></i>用户列表</h5>
                <button class="btn btn-light btn-sm" @click="fetchUsers" :disabled="loading">
                  <i class="bi bi-arrow-repeat me-1" :class="{'fa-spin': loading}"></i>
                  刷新
                </button>
              </div>
              <div class="card-body">
                <div class="table-responsive">
                  <table class="table table-hover">
                    <thead>
                      <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>邮箱</th>
                        <th>角色</th>
                        <th>平台</th>
                        <th>状态</th>
                        <th>创建时间</th>
                        <th>操作</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr v-for="u in admin.users" :key="u.user_id">
                        <td>{{ u.user_id }}</td>
                        <td>{{ u.username }}</td>
                        <td>{{ u.email }}</td>
                        <td>
                          <span class="badge" 
                                :class="u.role === 'admin' ? 'bg-danger' : 'bg-secondary'">
                            {{ u.role }}
                          </span>
                        </td>
                        <td>{{ u.platform }}</td>
                        <td>
                          <span class="badge" 
                                :class="u.status === 'active' ? 'bg-success' : 'bg-secondary'">
                            {{ u.status === 'active' ? '启用' : '停用' }}
                          </span>
                        </td>
                        <td>
                          {{ u.created_at ? new Date(u.created_at).toLocaleDateString() : '' }}
                        </td>
                        <td>
                          <button class="btn btn-sm btn-outline-primary me-1" 
                                  @click="toggleUserStatus(u.user_id)"
                                  :disabled="u.user_id === user.user_id">
                            {{ u.status === 'active' ? '停用' : '启用' }}
                          </button>
                          <button class="btn btn-sm btn-outline-danger" 
                                  @click="deleteUser(u.user_id)"
                                  :disabled="u.user_id === user.user_id || u.role === 'admin'">
                            删除
                          </button>
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 项目管理 -->
          <div v-if="admin.activeTab === 'projects'">
            <div class="row">
              <div class="col-md-6">
                <div class="card shadow-sm mb-4">
                  <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="bi bi-folder-plus me-2"></i>创建新项目</h5>
                  </div>
                  <div class="card-body">
                    <form>
                      <div class="mb-3">
                        <label class="form-label">项目名称</label>
                        <input type="text" class="form-control" required>
                      </div>
                      <div class="mb-3">
                        <label class="form-label">描述</label>
                        <textarea class="form-control" rows="3"></textarea>
                      </div>
                      <div class="mb-3">
                        <label class="form-label">生信分析流程名称</label>
                        <input type="text" class="form-control" required>
                      </div>
                      <button type="submit" class="btn btn-primary">
                        <i class="bi bi-plus-circle me-1"></i>创建项目
                      </button>
                    </form>
                  </div>
                </div>
              </div>
              
              <div class="col-md-6">
                <div class="card shadow-sm">
                  <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="bi bi-folder me-2"></i>项目列表</h5>
                  </div>
                  <div class="card-body">
                    <div class="table-responsive">
                      <table class="table table-hover">
                        <thead>
                          <tr>
                            <th>名称</th>
                            <th>流程</th>
                            <th>状态</th>
                            <th>操作</th>
                          </tr>
                        </thead>
                        <tbody>
                          <tr>
                            <td>RNA-Seq分析</td>
                            <td>rnaseq_pipeline</td>
                            <td>
                              <span class="badge bg-success">启用</span>
                            </td>
                            <td>
                              <button class="btn btn-sm btn-outline-danger">
                                删除
                              </button>
                            </td>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 项目分配 -->
          <div v-if="admin.activeTab === 'userProjects'">
            <div class="row">
              <div class="col-md-6">
                <div class="card shadow-sm mb-4">
                  <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="bi bi-link me-2"></i>分配项目给用户</h5>
                  </div>
                  <div class="card-body">
                    <form>
                      <div class="mb-3">
                        <label class="form-label">选择用户</label>
                        <select class="form-select" required>
                          <option>用户1</option>
                          <option>用户2</option>
                        </select>
                      </div>
                      <div class="mb-3">
                        <label class="form-label">选择项目</label>
                        <select class="form-select" required>
                          <option>项目1</option>
                          <option>项目2</option>
                        </select>
                      </div>
                      <button type="submit" class="btn btn-primary">
                        <i class="bi bi-link me-1"></i>分配项目
                      </button>
                    </form>
                  </div>
                </div>
              </div>
              
              <div class="col-md-6">
                <div class="card shadow-sm">
                  <div class="card-header bg-primary text-white">
                    <h5 class="mb-0"><i class="bi bi-diagram-3 me-2"></i>项目分配列表</h5>
                  </div>
                  <div class="card-body">
                    <div class="table-responsive">
                      <table class="table table-hover">
                        <thead>
                          <tr>
                            <th>用户</th>
                            <th>项目</th>
                            <th>状态</th>
                            <th>操作</th>
                          </tr>
                        </thead>
                        <tbody>
                          <tr>
                            <td>张三</td>
                            <td>RNA-Seq分析</td>
                            <td>
                              <span class="badge bg-success">启用</span>
                            </td>
                            <td>
                              <button class="btn btn-sm btn-outline-primary">
                                管理样本
                              </button>
                            </td>
                          </tr>
                        </tbody>
                      </table>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 样本管理 -->
          <div v-if="admin.activeTab === 'samples'">
            <div class="card shadow-sm">
              <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><i class="bi bi-database me-2"></i>样本管理</h5>
              </div>
              <div class="card-body">
                <div class="row">
                  <div class="col-md-6">
                    <div class="card mb-3">
                      <div class="card-header">
                        <h6><i class="bi bi-plus-circle me-1"></i>添加样本</h6>
                      </div>
                      <div class="card-body">
                        <form>
                          <div class="mb-3">
                            <label class="form-label">样本名称</label>
                            <input type="text" class="form-control" required>
                          </div>
                          <div class="mb-3">
                            <label class="form-label">分组名称</label>
                            <input type="text" class="form-control">
                          </div>
                          <button type="submit" class="btn btn-primary">
                            <i class="bi bi-plus-circle me-1"></i>添加样本
                          </button>
                        </form>
                      </div>
                    </div>
                  </div>
                  
                  <div class="col-md-6">
                    <div class="card">
                      <div class="card-header">
                        <h6><i class="bi bi-list me-1"></i>样本列表</h6>
                      </div>
                      <div class="card-body">
                        <div class="table-responsive">
                          <table class="table table-hover">
                            <thead>
                              <tr>
                                <th>名称</th>
                                <th>分组</th>
                                <th>操作</th>
                              </tr>
                            </thead>
                            <tbody>
                              <tr>
                                <td>Sample_001</td>
                                <td>实验组</td>
                                <td>
                                  <button class="btn btn-sm btn-outline-danger">
                                    删除
                                  </button>
                                </td>
                              </tr>
                            </tbody>
                          </table>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  `
};